
import {Socket} from "net";
import log from "./logger";
import * as iconv from 'iconv-lite'
import utils from "./utils";

const map = new Map<string, Socket>()

class Led {
    get(text: string, line: number) {
        const textbuf = iconv.encode(text, 'GB2312')
        const frameheader = utils.Str2Bytes('a5a5a5a5a5a5a5a5');
        const buf1 = utils.Str2Bytes('feff');
        const buf2 = utils.Str2Bytes('0080000000000000fe02');
        const buf3 = [42 - 6 + textbuf.length]
        const buf4 = utils.Str2Bytes('00a3060100000001');
        const buf5 = [33 - 6 + textbuf.length]
        const buf6 = utils.Str2Bytes('00000000');
        const buf7 = [(line - 1) * 32] // AreaY 48
        const buf8 = utils.Str2Bytes('00C0002000');
        const buf9 = [line - 1]
        const buf10 = utils.Str2Bytes('00000a0000000001010300020a');
        const buf11 = [textbuf.length]
        const buf12 = utils.Str2Bytes('000000');
        const buf13 = []
        for (let i = 0; i < textbuf.length; i++) {
            buf13.push(textbuf[i])
        }
        const pack = buf1.concat(buf2).concat(buf3).concat(buf4).concat(buf5).concat(buf6).concat(buf7)
            .concat(buf8).concat(buf9).concat(buf10).concat(buf11).concat(buf12).concat(buf13)
        let packStr = pack.map((value) => {
            return (value.toString(16).length === 1 ? '0' : '') + value.toString(16)
        }).join('')
        const crcStr = utils.crc(packStr)
        const buf14 = [parseInt(crcStr.substr(2, 2), 16), parseInt(crcStr.substr(0, 2), 16)]
        const framefooter = [0x5a]

        const escapebefore = pack.concat(buf14)
        const escapeafter: number[] = []
        escapebefore.forEach((value) => {
            if (value === 0xa5) {
                escapeafter.push(0xa6)
                escapeafter.push(0x02)
            } else if (value === 0xa6) {
                escapeafter.push(0xa6)
                escapeafter.push(0x01)
            } else if (value === 0x5a) {
                escapeafter.push(0x5b)
                escapeafter.push(0x02)
            } else if (value === 0x5b) {
                escapeafter.push(0x5b)
                escapeafter.push(0x01)
            } else {
                escapeafter.push(value)
            }
        })

        return new Uint8Array(
            frameheader.concat(escapeafter).concat(framefooter)
        )
    }

    async send(text: string, text2: string, text3: string, hostname: string) {
        const port = 5005
        let socket = map.get(hostname);
        if (socket) {
            log.info('发送数据:', hostname, text, text2, text3);
            const buf = this.get(text, 1)
            console.log(utils.Bytes2Str(buf));
            socket.write(buf)
            await utils.sleep(200)
            const buf2 = this.get(text2, 2)
            console.log(utils.Bytes2Str(buf2));
            socket.write(buf2)
            await utils.sleep(200)
            const buf3 = this.get(text3, 3)
            console.log(utils.Bytes2Str(buf3));
            socket.write(buf3)
        }else{
            socket = new Socket();
            socket.setEncoding('utf8');
            socket.connect(port, hostname, async () => {
                map.set(hostname, socket)
                log.info('重新连接成功，发送数据:', hostname, text, text2, text3);
                const buf = this.get(text, 1)
                console.log(utils.Bytes2Str(buf));
                socket.write(buf)
                await utils.sleep(200)
                const buf2 = this.get(text2, 2)
                console.log(utils.Bytes2Str(buf2));
                socket.write(buf2)
                await utils.sleep(200)
                const buf3 = this.get(text3, 3)
                console.log(utils.Bytes2Str(buf3));
                socket.write(buf3)
            });
            socket.on('data', function (msg) {
                log.info('led1 data', msg);
            });

            socket.on('error', function (error) {
                log.error('led error', error);
            });

            socket.on('close', () => {
                log.error('led 下线了');
            });

        }
    }
}

const led = new Led();
export default led;